package com.csdj.t309.utils;

import org.hibernate.validator.internal.util.privilegedactions.GetClassLoader;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * redis相关操作
 */
public class RedisUtil {
    private RedisUtil(){}

    static class Inner{
       static JedisPool pool;

        static {
            try {
                pool = initPool();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static JedisPool initPool() throws IOException {
        InputStream is = RedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties properties = new Properties();
        properties.load(is);
        String host = properties.getProperty("host","localhost");
        String portStr = properties.getProperty("port","6379");
        String password = properties.getProperty("password","123456");
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(20);
        config.setMinIdle(2);
        return new JedisPool(config,host,Integer.valueOf(portStr),3000,password);
    }

    private static Jedis getResource(){
        return Inner.pool.getResource();
    }

    public static String getString(String key){
        Jedis resource = null;
        try{
            resource = getResource();
            if(resource != null){
                return resource.get(key);
            }
            return null;
        }finally {
            if(resource != null){
                resource.close();
            }
        }
    }
}
